<?php

namespace App\Http\Controllers\Wx;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use EasyWeChat\Factory;
use App\Models\PlayerWechat;
use App\Models\Player;
use Illuminate\Support\Facades\Hash;

class LoginController extends Controller
{

    // 用户登录
    public function login(Request $request)
    {
        try {
            $code = $request->input('code');

            $app = Factory::miniProgram(config('wechat.mini_program.default'));

            $data = $app->auth->session($code);

            $openId = $data['openid'];

            $body = $request->post();

            $playerWechat = PlayerWechat::query()
                                        ->where('open_id', $openId)
                                        ->first();

            if (is_null($playerWechat)) {
                $playerWechat = new PlayerWechat();

                $playerWechat->player_id = 9999;
                $playerWechat->open_id = $openId;
                $playerWechat->nickname = $body['nickName'];
                $playerWechat->avatar = $body['avatarUrl'];
                $playerWechat->gender = $body['gender'];

                $playerWechat->save();
            }

            $attempt = Player::query()
                             ->find($playerWechat->player_id);

            if (is_null($attempt)) {
                abort(404, '玩家不存在');
            }

            $token = Auth::guard('wx')
                         ->attempt(['player' => $attempt->player, 'password' => 'secret']);

            if (!$token) {
                abort(403, '登陆失败');
            }

            return [
                'access_token' => $token,
                'token_type' => 'Bearer',
                'expires_in' => auth('admin')
                        ->factory()
                        ->getTTL() * 60,

            ];
        } catch (\Exception $exception) {
            abort(500, '登陆失败');
        }
    }
}
